package tp.pr5.instructions;

import tp.pr5.NavigationModule;
import tp.pr5.RobotEngine;
import tp.pr5.Rotation;
import tp.pr5.instructions.exceptions.InstructionExecutionException;
import tp.pr5.instructions.exceptions.WrongInstructionFormatException;
import tp.pr5.items.ItemContainer;

/**
 * Its execution rotates the robot This Instruction works if the robot writes TURN LEFT or RIGHT or GIRAR LEFT or RIGHT
 *
 */
public class TurnInstruction implements Instruction
{
	private Rotation rotation;
	private NavigationModule navigation;
	private RobotEngine engine;
	
	/**
	 * Default constructor
	 */
	public TurnInstruction()
	{
		this.engine = null;
		this.navigation = null;
	}
	
	/**
	 * Constructor with a rotation
	 * 
	 * @param rotation can be left or right
	 */
	public TurnInstruction(Rotation rotation)
	{
		this();
		this.rotation = rotation;
	}
	
	/**
	 * Parses the String returning an instance of RadarInstruction or throwing a WrongInstructionFormatException()
	 * 
	 * @param cad string given
	 */
	@Override
	public Instruction parse(String cad) throws WrongInstructionFormatException
	{		
		String[] entry = cad.toUpperCase().trim().split(" +");
		if((entry[0].equals("TURN") || entry[0].equals("GIRAR")) && entry.length == 2)
		{
			if(entry[1].equals("LEFT"))
			{
				rotation = Rotation.LEFT;
				return new TurnInstruction(rotation);
			}
			if(entry[1].equals("RIGHT"))
			{	
				rotation = Rotation.RIGHT;
				return new TurnInstruction(rotation);
			}
			throw new WrongInstructionFormatException();				
		}
		throw new WrongInstructionFormatException();
	}

	/**
	 * Fixes the current context, i.e., the robot engine and the navigation module
	 * 
	 * @param engine RobotEngine
	 * @param navigation NavigationModule
	 * @param robotContainer ItemContainer
	 * 
	 */
	@Override
	public void configureContext(RobotEngine engine, NavigationModule navigation, ItemContainer robotContainer) 
	{
		this.engine = engine;
		this.navigation = navigation;
		
	}

	/**
	 * Turns the robot left or right
	 */
	@Override
	public void execute() throws InstructionExecutionException 
	{
		try
		{
			this.navigation.rotate(rotation);
			this.engine.addFuel(-5);
			
		} catch(Exception e){
			throw new InstructionExecutionException();
		}
	}

	/**
	 * Returns a description of the Instruction syntax. The string does not end with the line separator. 
	 * It is up to the caller adding it before printing.
	 */
	@Override
	public String getHelp()
	{
		return "TURN|GIRAR < LEFT|RIGHT >";
	}

}
